package com.by_man.presenter.module_health_records.access_records;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.custom_layout.QQListView;
import com.by_man.repository.IpAddress;
import com.by_man.repository.PostJsonArrayRequest;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by man on 2017-03-16.
 */
public class MedicationRecordActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    private QQListView lv;
    private SwipeRefreshLayout mSwipeLayout;
    final ArrayList<HashMap<String, Object>> listItem = new ArrayList<>();
    private SimpleAdapter adapter;
    private RequestQueue rQueue;

    private static final int REFRESH_COMPLETE = 0X110;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg)
        {
            if (msg.what == REFRESH_COMPLETE) {
                // 重新请求数据
                listItem.clear();
                HashMap<String,String> params = new HashMap<>();
                params.put("token", UserInfos.token);
                JSONObject jsonObject = new JSONObject(params);
                PostJsonArrayRequest jsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.Now_Medication, jsonObject,
                        new Response.Listener<JSONArray>() {
                            @Override
                            public void onResponse(JSONArray jsonArray) {
                                UserInfos.Medinice_Report = jsonArray.toString();
                                JSONObject temp;
                                String drug_name ;
                                String drug_type ;
                                String drug_rate ;
                                String drug_dosage;
                                String drug_start;
                                String drug_create;
                                String state;
                                try {
                                    for (int j = 0; j < jsonArray.length(); j++) {
                                        temp = (JSONObject) jsonArray.get(j);
                                        HashMap<String, Object> map = new HashMap<String, Object>();
                                        drug_name = temp.getString("drug_name");
                                        drug_type = temp.getString("drug_type");
                                        drug_rate = temp.getString("drug_rate");
                                        drug_dosage = temp.getString("drug_dosage");
                                        drug_start = temp.getString("drug_start");
                                        drug_create = temp.getString("create_time");
                                        state = temp.getString("state");

                                        map.put("name", drug_name);
                                        map.put("type", drug_type);
                                        map.put("rate", drug_rate);
                                        map.put("dosage", drug_dosage);
                                        map.put("start", drug_start);
                                        map.put("create", drug_create);
                                        map.put("state", state);
                                        listItem.add(map);
                                    }
                                } catch (JSONException je) {
                                    je.printStackTrace();
                                }
                                adapter.notifyDataSetChanged();
                                mSwipeLayout.setRefreshing(false);
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.e("MedicationRecordError",volleyError.getMessage(),volleyError);
                                Toast.makeText(MedicationRecordActivity.this, "修改请求失败!",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                rQueue.add(jsonArrayRequest);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medication_record);
        //rQueue = Volley.newRequestQueue(this);
        rQueue = SharedApplication.getrQueue(getApplication());
        rQueue.start();
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, AccessRecordsActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                onBackPressed();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, AccessRecordsActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
//    }


    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        lv =(QQListView) findViewById(R.id.medinice_now_list);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorScheme(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        String report = UserInfos.Medinice_Report;
        if (null != report) {
            try {
                JSONArray jsonArray = new JSONArray(report);
                JSONObject temp;
                String drug_name;
                String drug_type;
                String drug_rate;
                String drug_dosage;
                String drug_start;
                String drug_create;
                String state;
                for (int j = 0; j < jsonArray.length(); j++) {
                    temp = (JSONObject) jsonArray.get(j);
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    drug_name = temp.getString("drug_name");
                    drug_type = temp.getString("drug_type");
                    drug_rate = temp.getString("drug_rate");
                    drug_dosage = temp.getString("drug_dosage");
                    drug_start = temp.getString("drug_start");
                    drug_create = temp.getString("create_time");
                    state = temp.getString("state");

                    map.put("name", drug_name);
                    map.put("type", drug_type);
                    map.put("rate", drug_rate);
                    map.put("dosage", drug_dosage);
                    map.put("start", drug_start);
                    map.put("create", drug_create);
                    map.put("state", state);
                    listItem.add(map);
                }
                adapter = new SimpleAdapter();
                lv.setAdapter(adapter);
            } catch (JSONException je) {
                je.printStackTrace();
            }
        } else {
            Toast.makeText(this,"出现未知错误，没有相应数据！",Toast.LENGTH_SHORT).show();
        }
        //长按删除当前用药
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> Views, View view, final int position, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(MedicationRecordActivity.this, "长按了第" + (position + 1) + "个", Toast.LENGTH_LONG).show();
                HashMap<String, String> item = (HashMap<String, String>) lv.getItemAtPosition(position);
                AlertDialog.Builder builder = new AlertDialog.Builder(MedicationRecordActivity.this);
                final String starttime = item.get("create");
                String drugname = item.get("name");
                builder.setMessage("确定停止对" + item.get("name") + "药品的食用吗？");
                builder.setTitle("操作提示");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        listItem.remove(position);
                        adapter.notifyDataSetChanged();
                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("token", UserInfos.token);
                        params.put("start", starttime);
                        PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST, IpAddress.Stop_Medication, params,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String s) {
                                        JSONObject json = null;
                                        try {
                                            json = new JSONObject(s);
                                            boolean isUpdate = json.getBoolean("isUpdate");
                                            if (isUpdate) {
                                                Toast.makeText(MedicationRecordActivity.this, "修改成功",
                                                        Toast.LENGTH_LONG).show();
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                },
                                new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError volleyError) {
                                        Log.e("MedicationRecordError",volleyError.getMessage(),volleyError);
                                        Toast.makeText(MedicationRecordActivity.this, "修改请求失败!",
                                                Toast.LENGTH_LONG).show();
                                    }
                                });
                        rQueue.add(stringRequest);
                    }
                });

                builder.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                            }
                        });
                builder.create().show();
                return true;
            }
        });

        Button button2 = (Button) findViewById(R.id.medinice_new);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MedicationRecordActivity.this, AddMedicationActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        Button button3 = (Button) findViewById(R.id.medinice_his);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MedicationRecordActivity.this, MedicationHistoryActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    public void onRefresh()
    {
        mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 2000);

    }

    class SimpleAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listItem.size();
        }

        @Override
        public Object getItem(int position) {
            return listItem.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            if (null == convertView) {
                convertView = View.inflate(MedicationRecordActivity.this, R.layout.item_listview_medication, null);
            }
            TextView tv1 = (TextView) convertView.findViewById(R.id.list_medinice_name);
            TextView type1 = (TextView) convertView.findViewById(R.id.list_medinice_type);
            TextView rate1 = (TextView) convertView.findViewById(R.id.list_medinice_rate);
            TextView amount1 = (TextView) convertView.findViewById(R.id.list_medinice_amount);   //剂量
            TextView start1 = (TextView) convertView.findViewById(R.id.list_medinice_star);

            //  这里应该使用listItem，使用jsonArray每次都只刷新大小固定的值temp = (JSONObject) jsonArray.get(position);
            HashMap<String, Object> map = new HashMap<String, Object>();
            map = listItem.get(position);
            String name = (String) map.get("name");
            tv1.setText((String) map.get("name"));
            type1.setText((String) map.get("type") + "mg/片");
            rate1.setText("每天" + ((String) map.get("rate")) + "次");
            amount1.setText((String) map.get("dosage") + "片(粒)/次");
            start1.setText((String) map.get("start"));

            final int pos = position;
            TextView delete = (TextView) convertView.findViewById(R.id.delete);
            delete.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          public void onClick(View v) {
                                              HashMap<String, String> item = (HashMap<String, String>) lv.getItemAtPosition(position);

                                              String cehua_starttime = item.get("create");
                                              listItem.remove(position);
                                              //  lv.setAdapter(new SimpleAdapter());
                                              //刷新列表
                                              notifyDataSetChanged();
                                              lv.turnToNormal();

                                              HashMap<String, String> params = new HashMap<String, String>();
                                              params.put("token", UserInfos.token);
                                              params.put("start", cehua_starttime);
                                              PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST, IpAddress.Stop_Medication, params,
                                                      new Response.Listener<String>() {
                                                          @Override
                                                          public void onResponse(String s) {
                                                              JSONObject json = null;
                                                              try {
                                                                  json = new JSONObject(s);
                                                                  boolean isUpdate = json.getBoolean("isUpdate");
                                                                  if (isUpdate) {
                                                                      Toast.makeText(MedicationRecordActivity.this, "修改成功",
                                                                              Toast.LENGTH_LONG).show();

                                                                  }
                                                              } catch (JSONException e) {
                                                                  e.printStackTrace();
                                                              }
                                                          }
                                                      },
                                                      new Response.ErrorListener() {
                                                          @Override
                                                          public void onErrorResponse(VolleyError volleyError) {
                                                              Log.e("MedicationRecordError", volleyError.getMessage(), volleyError);
                                                              Toast.makeText(MedicationRecordActivity.this, "修改请求失败!",
                                                                      Toast.LENGTH_LONG).show();
                                                          }
                                                      });
                                              rQueue.add(stringRequest);
                                          }
                                      });

            TextView editdrugView = (TextView) convertView.findViewById(R.id.edit_drug);
            editdrugView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HashMap<String, String> item = (HashMap<String, String>) lv.getItemAtPosition(position);
                    String rate = item.get("rate");
                    String dosage = item.get("dosage");
                    String type = item.get("type");
                    String start = item.get("start");
                    String name = item.get("name");
                    String createtime = item.get("create");
                    String state = item.get("state");
//                    Intent intent = new Intent(MedicationRecordActivity.this, themedinice_reset.class);
//                    intent.putExtra("extra_drugdosage", dosage);
//                    intent.putExtra("extra_type", type);
//                    intent.putExtra("extra_start", start);
//                    intent.putExtra("extra_rate", rate);
//                    intent.putExtra("extra_drugname", name);
//                    intent.putExtra("extra_createtime", createtime);
//                    intent.putExtra("state", state);
//                    startActivity(intent);
                }
            });
            return convertView;
        }
    }
}
